<template>
  <div class="main-layout">
    <!-- 加载状态 -->
    <div v-if="loading" class="layout-loading">
      <el-icon class="loading-icon">
        <LoadingIcon />
      </el-icon>
      <span>布局加载中...</span>
    </div>

    <template v-else>
      <!-- 侧边栏 -->
      <el-aside width="220px" class="app-sidebar">
        <div class="logo-container">
          <img src="@/assets/logo.svg" class="logo" /> <span style="padding-left: 2px;">项目管理系统</span>
        </div>
        <el-menu :default-active="activeMenu" router unique-opened background-color="#304156" text-color="#bfcbd9"
          active-text-color="#409EFF">
          <menu-item v-for="item in menuList" :key="item.path" :menu="item" />
        </el-menu>
      </el-aside>

      <!-- 主容器 -->
      <el-container>
        <!-- 顶部导航 -->
        <el-header class="app-header">
          <div class="header-right">
            <el-dropdown @command="setTheme" trigger="click">
              <el-button text circle>
                <el-icon :size="20">
                  <Sunny />
                </el-icon>
              </el-button>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item v-for="theme in themes" :key="theme.name" :command="theme.name"
                    :class="{ 'is-active': currentTheme === theme.name }">
                    {{ theme.label }}
                  </el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>

            <el-dropdown @command="handleUserCommand">
              <span class="user-info">
                <el-avatar :src="user.avatar" />
                <span>{{ user.name }}</span>
              </span>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item command="profile">个人中心</el-dropdown-item>
                  <el-dropdown-item command="password">修改密码</el-dropdown-item>
                  <el-dropdown-item divided command="logout">退出登录</el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </div>
        </el-header>

        <!-- 主内容区 -->
        <el-main class="app-main">
          <router-view />
        </el-main>
      </el-container>
    </template>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { useUserStore } from '@/store/user'
import axios from 'axios'
import { Loading as LoadingIcon, Sunny } from '@element-plus/icons-vue'
import MenuItem from './components/MenuItem.vue'

const router = useRouter()
const userStore = useUserStore()
const loading = ref(true)

const themes = [
  { name: 'light', label: '明亮' },
  { name: 'dark', label: '暗黑' }, 
  { name: 'blue', label: '蓝色' },
  { name: 'green', label: '绿色' }
]

const currentTheme = ref(localStorage.getItem('theme') || 'light')

const user = computed(() => userStore.userInfo || { name: '用户', avatar: '' })
const menuList = ref([])
const activeMenu = computed(() => router.currentRoute.value.path)

onMounted(async () => {
  try {
    // 应用保存的主题
    document.documentElement.className = currentTheme.value
    
    // 通过API获取菜单数据
    try {
      console.log('[MainLayout] 开始请求菜单数据...')
      console.log('Mock服务器状态:', {
        isMockEnabled: import.meta.env.VITE_APP_MOCK === 'true',
        env: import.meta.env.MODE
      })
      const startTime = Date.now()
      
      const response = await axios.get('/api/menu', {
        headers: {
          'Cache-Control': 'no-cache'
        }
      })
      
      console.log(`[MainLayout] 菜单API响应 (${Date.now() - startTime}ms):`, {
        status: response.status,
        statusText: response.statusText,
        data: response.data
      })
      
      if (!response.data) {
        throw new Error('API返回数据为空')
      }
      
      if (response.data?.code !== 200) {
        console.error('[MainLayout] 获取菜单失败:', {
          code: response.data?.code,
          message: response.data?.message || '未知错误',
          response: response.data
        })
        // 使用默认菜单作为回退
        menuList.value = [
          {
            path: '/',
            name: 'Home',
            title: '首页',
            icon: 'House',
            children: []
          },
          {
            path: 'test-form-controls',
            name: 'Test1',
            title: '测试页1',
            icon: '',
            children: []
          }
          ,
          {
            path: 'test-form-controls2',
            name: 'Test2',
            title: '测试页2',
            icon: '',
            children: []
          }
        ]
        return
      }
      
      if (!Array.isArray(response.data.data)) {
        throw new Error('菜单数据不是数组')
      }
      
      // 严格验证数据格式
      const validatedData = response.data.data.map(item => {
        if (!item.path || !item.title) {
          console.warn('[MainLayout] 无效的菜单项:', item)
          return null
        }
        return {
          path: item.path || '#',
          name: item.name || '',
          title: item.title || '未命名菜单',
          icon: item.icon || '',
          children: Array.isArray(item.children) ? 
            item.children.filter(child => child.path && child.title) : []
        }
      }).filter(Boolean) // 过滤掉无效项
      
              console.log('[MainLayout] 验证后的菜单数据:', validatedData)
        
              // 验证图标是否存在
              validatedData.forEach(menu => {
                if (menu.icon && !['HomeFilled', 'Document', 'User', 'Setting'].includes(menu.icon)) {
                  console.warn(`[MainLayout] 可能无效的图标名称: ${menu.icon}`)
                }
              })
      menuList.value = validatedData.length ? validatedData : [
        {
          path: '/',
          name: 'Home',
          title: '首页',
          icon: 'House',
          children: []
        }
      ]
      
    } catch (error) {
      console.error('[MainLayout] 获取菜单异常:', {
        error: error.message,
        request: error.config?.url,
        response: error.response?.data,
        stack: error.stack
      })
      
      // 使用默认菜单作为回退
      menuList.value = [
        {
          path: '/',
          name: 'Home',
          title: '首页',
          icon: 'House',
          children: []
        }
      ]
      
    } finally {
      loading.value = false
    }
  } catch (error) {
    console.error('加载菜单失败:', error)
  }
})

const setTheme = (theme) => {
  currentTheme.value = theme
  document.documentElement.className = theme
  // 保存主题偏好
  localStorage.setItem('theme', theme)
}

const handleUserCommand = (command) => {
  switch (command) {
    case 'profile':
      router.push('/profile')
      break
    case 'password':
      // 打开修改密码弹窗
      break
    case 'logout':
      userStore.logout()
      router.push('/login')
      break
  }
}
</script>

<style scoped>
.main-layout {
  height: 100vh;
  display: flex;
}

.app-sidebar {
  background-color: #304156;
  transition: width 0.3s;
}

.logo-container {
  height: 48px;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: var(--menu-bg-color);
  border-bottom: 1px solid var(--el-border-color-base);
}

.logo {
  height: 28px;
}

.app-header {
  height: 48px !important;
  display: flex;
  justify-content: flex-end;
  align-items: center;
  background: #fff;
  box-shadow: 0 1px 4px rgba(0, 21, 41, 0.08);
  line-height: 48px;
}

.app-main {
  background-color: #f0f2f5;
  padding: 16px;
  min-height: calc(100vh - 48px);
}

.header-right {
  display: flex;
  align-items: center;
  gap: 15px;
}

.user-info {
  display: flex;
  align-items: center;
  cursor: pointer;
  padding: 0 10px;
}

.user-info span {
  margin-left: 10px;
}

.app-main {
  background-color: #f0f2f5;
  padding: 20px;
  min-height: calc(100vh - 60px);
}

/* 保留原有加载样式 */
.layout-loading {
  display: flex;
  justify-content: center;
  align-items: center;
}

@keyframes rotate {
  from { transform: rotate(0deg); }
  to { transform: rotate(360deg); }
}
</style>